import time

from imutils import paths
import pickle
import cv2 as cv
import pandas as pd
import numpy as np


class process_img():
    """
    获取训练集
    """
    def __init__(self,h,w ):
        self.h = h
        self.w = w
        self.k_num=[1]

    def knum(self):

        return len(list(paths.list_images(".\img")))-1

    def get_data(self,nums):  ###h ,w 为照片重构后的大小

        columos = range(0, self.h * self.w + 1)
        train_data = pd.DataFrame(columns=columos)
        un_use_img = []  # 没有被当作训练数据的图片
        k = 0
        nums[0]=0
        ##################################################################################

        face_cascade = cv.CascadeClassifier('./haarcascade/haarcascade_frontalface_alt.xml')  # 初始化检测器

        lable = []
        for a in list(paths.list_images(".\img")):  ## 所有图片的路径
            z = a.split('\\')[2]
            lable.append(z)  # 标签

        lable = list(set(lable))   ## 去除重复的标签
        print(lable)
        filename_list = list(paths.list_images(".\img")) # 所有图片路径
        print(len(filename_list))
        for filename in filename_list:

            # print(nums[0])
            img_name = filename.split('\\')[2]  # 图片名字
            lb = list.index(lable, img_name)  # 获取标签对应的数值
            img = cv.imdecode(np.fromfile(filename, dtype=np.uint8), -1)  ####读取图片
            if len(np.shape(img)) == 3:
                gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
            else:
                gray = img
            faces_num= face_cascade.detectMultiScale(gray)
            # print("11111111111")
            if len(faces_num) == 1:  ####照片里有一个人可以作为训练数据

                for (face_x, face_y, face_w, face_h) in faces_num:  ########人脸的所有位置
                    new_img = cv.resize(gray[face_y:face_y + face_h, face_x:face_x + face_w], (self.h, self.w), interpolation=cv.INTER_NEAREST)
                    # print("shape:", np.shape(new_img))
                    # print(self.h, self.w)
                    train_data.loc[k] = np.append(new_img.ravel(), lb)
                    k = k + 1

                    # print("aaaaaaa")
                    # time.sleep(0.2)
                    # print("zzzzzzzzz")
            if len(faces_num) > 1:

                un_use_img.append(filename)
            nums[0] = nums[0] + 1
        print("完成")





        with open("./data/train_data", 'wb') as f:
            pickle.dump(train_data, f)
        with open("./data/txt_img", 'wb') as f:
            pickle.dump(un_use_img, f)
        with open("./data/lablae", 'wb') as f:
            pickle.dump(lable, f)
        with open("./data/img_shape", 'wb') as f:
            pickle.dump([self.h, self.w], f)
        return 0

# n = 0
# a = process_img(32,32,n)
# a.get_data()